import util from '../util.js';
import pool from './db.js';

// 查询所有音乐
export async function getAllMusic() {
    const [rows] = await pool.query('SELECT * FROM music');
    return rows;
}

// 根据ID查询音乐
export async function getMusicById(id) {
    const [rows] = await pool.query('SELECT * FROM music WHERE id = ?', [id]);
    return rows[0];
}

export async function getRandomMusic() {
    // 使用ORDER BY RAND()进行随机排序，LIMIT 1只取一条记录
    // 注意：RAND()在MySQL中有效，其他数据库可能需要不同函数（如PostgreSQL使用RANDOM()）
    const [rows] = await pool.query('SELECT * FROM music ORDER BY RAND() LIMIT 1');
    return rows[0];
}

// 添加音乐
export async function addMusic(music) {
    const { name, url, package_id } = music;
    const now = util.getDatetime();
    const [result] = await pool.query(
        'INSERT INTO music (name, url, package_id, create_time, update_time) VALUES (?, ?, ?, ?, ?)',
        [name, url, package_id, now, now]
    );
    return result.insertId;
}

// 更新音乐
export async function updateMusic(id, music) {
    const { name, url } = music;
    const now = new Date();
    const [result] = await pool.query(
        'UPDATE music SET name = ?, url = ?, package_id=?, update_time = ? WHERE id = ?',
        [name, url, package_id, now, id]
    );
    return result.affectedRows > 0;
}

export async function getMusicByPackageId(package_id) {
    const [rows] = await pool.query('SELECT * FROM music WHERE package_id = ?', [package_id]);
    return rows;
}

// 删除音乐
export async function deleteMusic(id) {
    const [result] = await pool.query('DELETE FROM music WHERE id = ?', [id]);
    return result.affectedRows > 0;
}

export async function getRandomMusicByPackageId(package_id) {
    // 使用ORDER BY RAND()进行随机排序，LIMIT 1只取一条记录
    // 注意：RAND()在MySQL中有效，其他数据库可能需要不同函数（如PostgreSQL使用RANDOM()）
    const [rows] = await pool.query('SELECT * FROM music Where package_id = ? ORDER BY RAND() LIMIT 1',
        [package_id]);
    return rows[0];
}